package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/3/24 16:52
 * @Version 1.0
 */

@Component
public class AdminManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private AdminService adminService;

    //生成验证码
    public LineCaptcha verification(String uuid) {

        //使用hutool制作验证码
        LineCaptcha lineCaptcha = new LineCaptcha(200, 100);

        //验证码存入redis中（五分钟有效）
        stringRedisTemplate.opsForValue()
                .set(ConstantUtil.ADMIN_CODE + uuid, lineCaptcha.getCode(), Duration.ofMinutes(5));

        //返回验证码对象
        return lineCaptcha;


    }


    //用户登录
    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {

        //获取验证码
        String code = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        //对比验证码
        if (!StrUtil.equals(code, verificationCode)) {
            throw new BusinessException("验证码错误");
        }
        //根据账号密码查询数据库
        //md5加密一下
        password = SecureUtil.md5(password);
        Admin admin = adminService.login(username, password);
        if (ObjectUtil.isEmpty(admin)) {

            throw new BusinessException("用户密码错误");

        }
        //登录成功
        //制作token
        admin.setPassword(null);
        Map<String, Object> claims = BeanUtil.beanToMap(admin);
        String token = JwtUtil.createToken(claims);
        //admin转json存到redis
        String json = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));

        //删除redis中的验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE + uuid);
        //返回token
        HashMap result = new HashMap();
        result.put("token", token);
        return ResponseEntity.ok(result);

    }

    //验证token-获取用户信息
    public Admin findAdminByToken(String token) {

        //前端有一个习惯，携带token会加上 Bearer token.........
        token = token.replace("Bearer ", "");

        //根据token查询redis
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);
        if (StrUtil.isEmpty(json)) {
            return null;
        }

        //将json转为admin对象
        Admin admin = JSON.parseObject(json, Admin.class);

        //redis续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));

        return admin;

    }

    // 用户退出
    public void logout(String token) {
        // 0. 前端有一个习惯，携带token会加上 Bearer token.........
        token = token.replace("Bearer ", "");// Bearer后面有一个空格。。。
        // 1.删除redis中token
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN + token);
    }
}
